import { ref, reactive, computed, toRefs } from 'vue'
import { ElMessage } from 'element-plus'
import type { ApiListResponse, PaginationParams } from '@/types'

interface TableState<T> {
  list: T[]
  total: number
  loading: boolean
  params: PaginationParams
}

/**
 * 通用表格数据管理组合式函数
 * @param api API接口函数
 * @param initialParams 初始查询参数
 * @returns 表格状态和操作方法
 */
export function useTable<T>(
  api: (params: any) => Promise<ApiListResponse<T>>,
  initialParams: Record<string, any> = {}
) {
  const state = reactive<TableState<T>>({
    list: [],
    total: 0,
    loading: false,
    params: {
      page: 1,
      limit: 10,
      keywords: '',
      ...initialParams,
    },
  })

  /**
   * 加载数据
   */
  const loadData = async () => {
    try {
      state.loading = true
      const response = await api(state.params)

      if (response.code === 0) {
        // 修复类型错误：使用正确的类型转换
        state.list = response.data.list as any
        state.total = response.data.total
      } else {
        ElMessage.error(response.msg || '获取数据失败')
      }
    } catch (error) {
      console.error('加载数据失败:', error)
      ElMessage.error('网络错误，请稍后重试')
    } finally {
      state.loading = false
    }
  }

  /**
   * 搜索数据
   */
  const search = (searchParams: Record<string, any> = {}) => {
    state.params = {
      ...state.params,
      ...searchParams,
      page: 1,
    }
    loadData()
  }

  /**
   * 重置搜索
   */
  const reset = () => {
    state.params = {
      page: 1,
      limit: 10,
      keywords: '',
      ...initialParams,
    }
    loadData()
  }

  /**
   * 分页变化
   */
  const changePage = (page: number) => {
    state.params.page = page
    loadData()
  }

  /**
   * 页面大小变化
   */
  const changePageSize = (pageSize: number) => {
    state.params.limit = pageSize
    state.params.page = 1
    loadData()
  }

  /**
   * 刷新当前页
   */
  const refresh = () => {
    loadData()
  }

  // 计算属性
  const hasData = computed(() => state.list.length > 0)
  const isEmpty = computed(() => !state.loading && state.list.length === 0)

  return {
    // 状态
    ...toRefs(state),

    // 计算属性
    hasData,
    isEmpty,

    // 方法
    loadData,
    search,
    reset,
    changePage,
    changePageSize,
    refresh,
  }
}
